require(['init'], function () {
    //公司的初始密码
    var needPw = true;
    var $name = $('[name=name]')
    var $account = $('[name=account]')
    var $tuid = $('[name=tuid]')
    var $genderWrap = $('.genderWrap')
    var $courseType = $('#J_coursetypes');
    var $phone = $('[name=phone]')
    var $status = $('[name=status]')
    var $classInNo = $('[name=classin_no]')
    var $photo = $('#J_img')
    var $title = $('[name=title]')
    var $resume = $('#J_resume_filename')
    var $email = $('[name=email]')
    var $introduce = $('[name=introduce]');
    var $studentMax = $('[name="teach_student_count"]')
    var $lessontime = $('[name="lessontime_text"]')
    var $submitBtn = $('#J_teacheradd');
    var $imgUpload = $('#J_imgupload');
    var $resumeUpload = $('#J_resume');
    var $education = $('#J_eduction');
    var $workExp = $('#J_workexp');
    var tuid = location.search.urlToObj().tuid;
    if (tuid) {
        $submitBtn.val(i18next.t('info.save'));
        $account.parents('.formLi').show();
        $('#resetpassword').show();
        $('#classIntest').hide();
        $classInNo.attr("readonly", "readonly")
        $('.breadcrumb .active a').text(i18next.t('info.redact')).attr('href', 'javascript:void(0)')
    }
    function getFileNameByPath(src) {
        return src.replace(/^.+\/([^\/]+)$/, function () {
            if (arguments[1]) {
                return arguments[1]
            }
            return ''
        });
    }

    function loadCourseTypes(callback) {
        ajaxMethod({
            url: '/api/coursetypes',
            success: function (data) {
                $.each(data, function (i, item) {
                    var checkItem = '<span class="check-item">\
            <span class="icon icon-size-16 icon-checkbox" data-type="checkbox">\
              <input type="checkbox" name="coursetype" value="' + item.coursetypeuid + '">\
            </span><span data-type="label">' + item.coursetypename + '</span>\
          </span>&nbsp;';
                    $('#J_coursetypes').append(checkItem);
                });

                callback && callback();
            }
        })
    }

    function imgUpload($container) {
        var $uploadCoverBox = $container.find('.icon-uploadimg')
        var $uploadCoverThumb = $uploadCoverBox.find('img')
        var $uploadInput = $uploadCoverBox.find('input')

        var coverUploadInput = new UploadInput({
            $dom: $uploadInput,
            done: function (uploadImgSrc) {
                console.log(uploadImgSrc);
                var uploadImgFullSrc = '/api/file?u=' + uploadImgSrc;

                if (uploadImgSrc) {
                    new ImgCropTool({
                        imgSrc: uploadImgFullSrc,
                        cropSize: [200, 200, 'courseCover'],
                        success: function (imgSrc) {
                            var imgCropSrc = '/api/file?u=' + imgSrc;
                            $uploadCoverBox.attr('data-value', imgCropSrc);
                            $uploadCoverThumb.attr('src', imgCropSrc);
                        }
                    })
                }
            }
        });
    }

    function resumeUpload($container) {
        var $uploadCoverBox = $container.find('.icon-upload')
        var $uploadCoverThumb = $uploadCoverBox.find('.J_resume_filename')
        var $uploadInput = $uploadCoverBox.find('input')
        var coverUploadInput = new UploadInput({
            $dom: $uploadInput,
            done: function (uploadSrc) {
                console.log(uploadSrc);
                var uploadFullSrc = '/api/file?u=' + uploadSrc;
                var parseSrc = getFileNameByPath(uploadSrc);

                if (uploadSrc) {
                    $uploadCoverBox.hide();
                    $('#J_resume_filename').attr('href', uploadFullSrc).text(parseSrc).css('text-decaration', 'underline');
                    $('.J_file_wrap').show()
                    return;
                }
            }
        });
    }

    function ExperienceTool(options) {

        function ExpItem(options) {
            options = options || {};
            this.tips = options.tips || '请输入';
            this.data = options.data || {};
            this.$dom = $('<div style="width: 920px;margin-bottom:15px;"></div>');

            this.yearMonthInputStart = new YearMonthInput(); //
            this.yearMonthInputEnd = new YearMonthInput(); //

            this.$dom.append(this.yearMonthInputStart.$dom);
            this.$dom.append(' ~ ');
            this.$dom.append(this.yearMonthInputEnd.$dom);
            this.$dom.append('<span>&nbsp;&nbsp;&nbsp;&nbsp;</span>')

            this.$textInput = $('<input type="text" class="form-control J_text" style="width:500px;" placeholder="' + options.tips + '" />').appendTo(this.$dom) //

            this.$rightbtn = $('<span class="icon icon-size-16 icon-plus-square" style="margin-left:15px;"></span>').appendTo(this.$dom);
            this.$rightbtn.on('click', function () {
                var $this = $(this);
                if ($this.hasClass('icon-plus-square')) {
                    var expItem = new ExpItem({tips: options.tips});
                    expItem.$rightbtn.removeClass('icon-plus-square').addClass('icon-less-square');
                    $this.parent().after(expItem.$dom);
                } else {
                    var index = $this.parent().index();
                    $this.parent().remove();
                }
            })

            if (this.data) {
                this.yearMonthInputStart.value(+new Date(this.data.begindate));
                this.yearMonthInputEnd.value(+new Date(this.data.enddate));
                this.$textInput.val(this.data.remark);
            }
        }

        function ExperienceList(options) {
            options = options || {};

            this.$dom = $('<div></div>');
            this.data = options.data;
            this.tips = options.tips || '请输入';
            this.instanceList = [];

            if (this.data && this.data.length) {
                this.init();
            } else {
                this.addItem();
            }
        }

        ExperienceList.prototype = {
            constructor: ExperienceTool,
            addItem: function (data) {
                var expItem = new ExpItem({
                    tips: this.tips,
                    data: data
                })
                if (this.$dom.children().length > 0) {
                    expItem.$rightbtn.removeClass('icon-plus-square').addClass('icon-less-square');
                }
                this.$dom.append(expItem.$dom)
            },
            init: function () {
                var _this = this;
                $.each(this.data, function (i, item) {
                    _this.addItem(item);
                })
            },
            getValue: function () {
                var _this = this;
                this.data = []
                this.$dom.children().each(function (i, item) {
                    var $item = $(item);
                    var $timeInputStart = $($item.find('[data-type="timeinput"]')[0]);
                    var $timeInputEnd = $($item.find('[data-type="timeinput"]')[1]);

                    var yearStart = $timeInputStart.find('.selectInput')[0].value;
                    var monthStart = $timeInputStart.find('.selectInput')[1].value;

                    var yearEnd = $timeInputEnd.find('.selectInput')[0].value;
                    var monthEnd = $timeInputEnd.find('.selectInput')[1].value;

                    var text = $.trim($item.find('.J_text').val())
                    if (yearStart == "" || monthStart == "" || yearEnd == "" || monthEnd == "" || text == "") {
                        return true;
                    }

                    _this.data.push({
                        startTime: new Date(yearStart, monthStart - 1).getTime(),
                        endTime: new Date(yearEnd, monthEnd - 1).getTime(),
                        text: text
                    })
                })

                return this.data;
            }
        }

        this.expTool = new ExperienceList(options);
        this.$dom = this.expTool.$dom;

    }

    var eduExpTool;
    var workExpTool;

    function loadTeacherData(tuid, callback) {
        ajaxMethod({
            url: '/api/teacher/' + tuid,
            success: function (data) {
                if (data.status == 1) {
                    $('#status').find('input').click()
                }
                $name.val(data.lastname);
                $account.val(data.account);
                $genderWrap.find('input[value="' + data.sex + '"]').click();
                $phone.val(data.mobile);
                $classInNo.val(data.ClassInNo);
                $.each(data.coursedesc, function (i, item) {
                    $courseType.find('input[value="' + item + '"]').click()
                })

                $photo.attr('src', data.photo)
                $imgUpload.find('.icon-uploadimg').attr('data-value', data.photo)
                $email.val(data.email)
                $title.val(data.title)
                $introduce.val(data.introduce)
                $studentMax.val(data.remark1)
                $lessontime.val(data.remark2)

                if (data.resume) {
                    $('.icon-upload').hide()
                    $('.J_file_wrap').show().find('a').attr('href', data.resume).text(getFileNameByPath(data.resume)).css('text-decoration', 'underline');
                }


                $resume.attr('href', data.resume);

                eduExpTool = new ExperienceTool({
                    tips: '请输入就读学校和学历,如 某某大学（本科）',
                    data: data.educations
                });
                $education.append(eduExpTool.$dom);

                workExpTool = new ExperienceTool({
                    tips: '请输入工作单位',
                    data: data.experiences
                });
                $workExp.append(workExpTool.$dom);

                $('[name=tuid]').val(data.teacheruid);
                (typeof callback == 'function') && callback()
            }
        })
    }

    function submitTeacherData() {
        var sex = $('[name="gender"]:checked').val()
        if (sex == undefined) {
            var checkResult = {
                followTips: true,
                result: '请选择性别',
                status: false
            }
            FormCheck.checkTips($('.J_gender_help'), checkResult);
        }

        var courseId = $('[name="coursetype"]:checked').val();
        // if(courseId == undefined) {
        //   var checkResult = {
        //     followTips: true,
        //     result: '请选择教授课程',
        //     status: false
        //   }
        //   FormCheck.checkTips($('.J_coursetype_help'), checkResult);
        // }

        if (FormCheck.childrenInputCheck($('#J_teacheradd_wrap'))) {
            var name = $name.val();
            var phone = $phone.val()
            var classInNo = $classInNo.val()
            var courseIdArr = [];
            $('[name="coursetype"]:checked').each(function (i, item) {
                courseIdArr.push(item.value)
            })
            var photo = $('#J_uploadCover img').attr('src') || '';
            var email = $email.val()
            var title = $title.val()
            var password = $('[name="pw"]').val()
            var introduce = $introduce.val()
            var remark1 = $studentMax.val()
            var remark2 = $lessontime.val()
            var resume = $resume.attr('href')

            var educationValueArr = eduExpTool.expTool.getValue();
            var workValueArr = workExpTool.expTool.getValue();

            var educationPostArr = []
            $.each(educationValueArr, function (i, item) {
                educationPostArr.push({
                    begindate: new Date(item.startTime).Format('YYYY-MM-DD'),
                    enddate: new Date(item.endTime).Format('YYYY-MM-DD'),
                    remark: item.text
                })
            })

            var workPostArr = []
            $.each(workValueArr, function (i, item) {
                workPostArr.push({
                    begindate: new Date(item.startTime).Format('YYYY-MM-DD'),
                    enddate: new Date(item.endTime).Format('YYYY-MM-DD'),
                    remark: item.text
                })
            })
            if ($('#status').hasClass('checked')) {
                $status.val('1')
            } else {
                $status.val('0')
            }
            var postData = {
                lastname: name,
                sex: sex,
                mobile: phone,
                status: $status.val(),
                ClassInNo: classInNo,
                coursedesc: courseIdArr,
                photo: photo,
                resume: resume,
                email: email,
                title: title,
                introduce: introduce,
                remark1: remark1,
                remark2: remark2,
                educations: educationPostArr,
                //password:password,
                experiences: workPostArr

            }

            function gotoTeacherList() {
                location.href = 'teacherlist.html';
            }

            // $submitBtn.prop('disabled', true);
            if (tuid != undefined) {
                ajaxMethod({
                    url: '/api/teacher/' + tuid,
                    method: 'put',
                    data: $.extend({}, postData, {teacheruid: tuid}),
                    success: function (data,status) {
                        // $submitBtn.prop('disabled', false);
                        if (status.code == 0) {
                            gotoTeacherList();
                        } else {
                            _Tips(status.message);
                        }
                    }
                })
            } else {

              if (needPw = false) {
                    ajaxMethod({
                        url: '/api/teacher',
                        method: 'post',
                        data: postData,
                        success: function (data) {
                            if (status.code == 0) {
                                gotoTeacherList();
                            } else {
                                _Tips(status.message);
                            }
                        }
                    })
                } else {
                    ajaxMethod({
                        url: '/api/teacher',
                        method: 'post',
                        data: $.extend({}, postData, {password: password}),
                        success: function (data, status) {
                            if (status.code == 0) {
                                gotoTeacherList();

                            } else {
                                _Tips(status.message);
                            }
                        }
                    })
                }

            }

        }
    }

    //检测
    var registerDefaultPwd = "";
    ajaxMethod({
        url: '/api/organization/1',
        type: 'get',
        success: function (data) {
            registerDefaultPwd = data.registerDefaultPwd;
        }
    })
    $('[name="classin_no"]').on('blur', function () {
        classIntest(true);
    })
    var classin_nov = "";

    function classIntest(cl) {
        classin_nov = $('[name="classin_no"]').val();
        ajaxMethod({
            url: '/api/eeo/check',
            method: 'post',
            data: {account: classin_nov},
            success: function (data, status) {
                if (status.code == 0) {
                    if (data == "true") {
                        $('.pw').hide();
                        $('#prompt').show();
                        $('#noprompt').hide();
                        $("#resetpassword").attr("disabled", false);
                        needPw = false;
                    } else {
                        $('.pw').show();
                        $('#noprompt').show();
                        $('[name="pw"]').val(registerDefaultPwd);
                        $('#prompt').hide();
                        needPw = true;
                        $("#resetpassword").attr("disabled", true);
                    }
                } else {
                    if (data == "true") {
                        $('.pw').hide();
                        $('#prompt').show();
                        $('#noprompt').hide();
                        $("#resetpassword").attr("disabled", false);
                        needPw = false;
                    } else {
                        if ($('input[name="classin_no"]').val() != "") {
                            $('input[name="classin_no"]').next(".inputErrorTips").css({
                                "display": "block",
                                "margin-left": "132px"
                            }).text(status.message);
                        }
                    }
                }
            }

        })
    }

    $('[name="pw"]').on('blur', function () {
        if ($('[name="pw"]').val() != "") {
            $('#prompt').hide();
            $('#noprompt').hide();
        } else {
            $('#noprompt').show();
        }
    })
    //重置密码
    var account = "";
    $("#resetpassword").on('click', function () {
        account = $('[name="classin_no"]').val();
        //console.log(account)
        reset()
    })
    function reset() {
        var $ClassInDom = $('<div class="formList" id="J_teacheradd_wrap" style="margin-top:12px;">\
          <div class="formLi" >\
            <div class="formLi" >\
              <div class="formTitle required">\
                  <span>' + i18next.t('reset.newpassword') + '</span>\
              </div>\
              <div class="formContent">\
                  <input class="form-control" data-formcheck="length" type="text"  name="passwordnew" style="width:226px;">\
              </div>\
          </div>\
          <div class="formLi" >\
              <div class="formTitle required">\
                  <span>' + i18next.t('reset.confirmnewpassword') + '</span>\
              </div>\
              <div class="formContent">\
                  <input class="form-control" data-formcheck="length" type="text"  name="passwordold" style="width:226px;">\
                  <p style="color:red;display:none;margin-top:30px;" class="p">' + i18next.t('reset.twice') + '</p>\
              </div>\
            </div>\
          </div>');
        var popUpBox = new PopUpBox({
            type: 'dom',
            style: 'default contentScroll',
            //submitBtnType:false,
            submitBtnType: 'alert',
            titleText: i18next.t('reset.set'),//'请输入要设置的密码',
            show: true,
            content: $ClassInDom,
            callback: {
                yes: function (e) {
                    var passwordold = $ClassInDom.find('[name="passwordold"]').val();
                    var passwordnew = $ClassInDom.find('[name="passwordnew"]').val();
                    if (passwordold != "" || passwordnew != "") {
                        if (passwordold != passwordnew) {
                            $('.p').show();
                            return false;
                        } else {
                            $('.p').hide();
                            ajaxMethod({
                                url: '/api/eeo/reset',
                                method: 'post',
                                data: {
                                    account: account,
                                    password: passwordold
                                },
                                success: function (data, status) {
                                    if (status.code != 0) {
                                        _Tips(status.message)
                                    }
                                }
                            })
                        }
                    } else {
                        return false;
                    }

                }
            },
            position: {
                width: 480,
                height: 304,
            }
        })
        popUpBox.submitBtnBox.$dom.css('text-align', 'right')
    }

    function bindSubmit() {
        $submitBtn.on('click', submitTeacherData)
        $('body').on('click', '#J_resume .icon-delete', function () {
            var _this = this;
            var returnVal = confirm('确定删除该简历?')
            if (returnVal) {
                ajaxMethod({
                    url: '/api/teacher/' + tuid + '/resume',
                    method: 'delete',
                    success: function (data, status) {
                        if (status.code == 0) {
                            $(_this).parent().hide().next().show();
                        }
                    }
                })
            }
        })
    }

    imgUpload($imgUpload);
    resumeUpload($resumeUpload);

    // //同步手机号到classInNo,只同步一次
    // $phone.on('blur', function () {
    //   if(FormCheck.inputCheck($(this), true).status) {
    //       if(!$classInNo.val()) {
    //         $classInNo.val($(this).val())
    //       }
    //   }
    // })
    bindSubmit();

    if (tuid) {
        //编辑
        loadCourseTypes(function () {
            loadTeacherData(tuid);
        });
    } else {
        //创建
        loadCourseTypes();
        var eduExpTool = new ExperienceTool({tips: '请输入就读学校和学历,如 某某大学（本科）'});
        $education.append(eduExpTool.$dom);

        var workExpTool = new ExperienceTool({tips: '请输入工作单位'});
        $workExp.append(workExpTool.$dom);
    }

})
